package com.gxuwz.medical.domain.area;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gxuwz.medical.database.DBUtil;

/**
 * 行政区域模块类
 * @author 沉羽墨玖
 *
 */
public class Area {
	//区域编码:镇、村、组
	private String areacode;
	//上一级
	private Area parent;
	//行政区域名称
	private String areaName;
	//行政区域级别：1表示镇级，2表示村，3表示组
	private Integer grade;

	public Area() {

	}

	public Area(String areacode, String areaName, int grade) {
		super();
		this.areacode = areacode;
		this.areaName = areaName;
		this.grade = grade;
	}

	public Area getParent() {
		return parent;
	}

	public void setParent(Area parent) {
		this.parent = parent;
	}

	public Area(String areacode) throws Exception {
		this.areacode = areacode;
		loadDB(areacode);

	}

	public List<Area> findAll() {
		List<Area> areaList = new ArrayList<Area>();

		return areaList;
	}

	public void load(String areacode) throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.getConn();
			pstmt = conn
					.prepareStatement("select * from area where areacode=?");
			int index = 1;
			pstmt.setString(index, areacode);
			rs = pstmt.executeQuery();
			if (rs != null && rs.next()) {
				this.areacode = rs.getString("areacode");
				this.areaName = rs.getString("areaName");
				this.grade = rs.getInt("grade");
			}
		} catch (SQLException e) {
			throw new SQLException("Chronicdis with id " + areacode
					+ " could not be loaded from the database.");
		} finally {
			DBUtil.close(rs, pstmt, conn);
		}

	}

	/**
	 * 添加子一级行政区域
	 * 
	 * @param areaPid
	 *            -所属行政区域
	 * @param areaName
	 * @throws Exception
	 */
	public void addArea(String areaPid, String areaName) throws Exception {
		Connection conn = null;
		try {
			// 加载父节点id的对象
			this.parent = new Area(areaPid);
			this.areaName = areaName;
			this.grade = this.parent.getGrade() + 1;
			// 自动编号
			this.areacode = createareaId();
			conn = DBUtil.getConn();
			// 开启手动提交事务
			conn.setAutoCommit(false);
			// 保存到数据库
			saveToDB(conn);
			// 提交事务
			conn.commit();
		} catch (Exception e) {
			if (conn != null) {
				conn.rollback();
			}
			throw e;
		} finally {
			DBUtil.close(conn);
		}
	}

	private void saveToDB(Connection conn) throws SQLException {

		PreparedStatement pstmt = null;
		try {
			StringBuffer sqlBuff = new StringBuffer(
					"insert into area(areacode,areaName,grade)");
			sqlBuff.append("values(?,?,?)");
			pstmt = conn.prepareStatement(sqlBuff.toString());
			pstmt.setString(1, this.areacode);
			pstmt.setString(2, this.areaName);
			pstmt.setInt(3, this.grade);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			throw e;
		} finally {
			DBUtil.close(pstmt);
		}
	}

	public void edit() throws SQLException {
		Connection conn = null;
		try {
			conn = DBUtil.getConn();
			// 开启手动提交事务
			conn.setAutoCommit(false);
			// 保存到数据库
			editToDB(conn);
			// 提交事务
			conn.commit();
		} catch (SQLException e) {
			conn.rollback();
			throw e;
		} finally {
			DBUtil.close(conn);
		}
	}

	private void editToDB(Connection conn) throws SQLException {
		PreparedStatement pstmt = null;
		try {
			StringBuffer sqlBuff = new StringBuffer(
					"update area t set t.areaName=?,t.grade=? where t.areacode=?");
			pstmt = conn.prepareStatement(sqlBuff.toString());
			pstmt.setString(1, this.areaName);
			pstmt.setInt(2, this.grade);
			pstmt.setString(3, this.areacode);
			pstmt.executeUpdate();

		} catch (SQLException e) {
			throw new SQLException("Failed to update area  !", e);
		} finally {
			DBUtil.close(pstmt);
		}

	}

	public void del(String areacode) throws SQLException {
		Connection conn = null;
		this.areacode = areacode;
		try {
			conn = DBUtil.getConn();
			conn.setAutoCommit(false);
			deleteFromDB(conn);
			conn.commit();
		} catch (SQLException e) {
			conn.rollback();
			throw e;
		} finally {
			DBUtil.close(conn);
		}

	}

	private void deleteFromDB(Connection conn) throws SQLException {
		PreparedStatement pstmt = null;
		try {
			StringBuffer sqlBuff = new StringBuffer(
					"delete from area where areacode=?");
			pstmt = conn.prepareStatement(sqlBuff.toString());
			pstmt.setString(1, this.areacode);
			pstmt.executeUpdate();

		} catch (SQLException e) {
			throw new SQLException("Failed to delete record from table !", e);
		} finally {
			DBUtil.close(pstmt);

		}

	}

	private void loadDB(String areaId) throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.getConn();
			pstmt = conn
					.prepareStatement("select * from area where areacode=?");
			int index = 1;
			pstmt.setString(index, this.areacode);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				this.areacode = rs.getString("areacode");
				this.areaName = rs.getString("areaName");
				this.grade = (int) rs.getByte("grade");

			}
		} catch (SQLException e) {
			throw e;
		} finally {
			DBUtil.close(rs, pstmt, conn);
		}
	}

	/**
	 * 自动生成行政区域编号
	 * 
	 * @return
	 * @throws SQLException
	 */
	private String createareaId() throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String areaPid = this.parent.getAreacode();
		int grade = this.parent.getGrade() + 1;
		String sql = "select max(areacode) from area where areacode like'"
				+ areaPid + "%' and grade=" + grade;

		try {
			conn = DBUtil.getConn();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			String maxcode = "";
			Integer number = 1;
			if (rs.next()) {
				maxcode = rs.getString(1);
			}

			if (maxcode != null) {
				int beginIndex = maxcode.length() - 2;
				String no = maxcode.substring(beginIndex);
				number = Integer.parseInt(no);
				++number;
				// 使用0补足位数
				no = String.format("%02d", number);
				maxcode = this.parent.getAreacode() + no;
			} else {
				String no = String.format("%02d", number);
				maxcode = this.parent.getAreacode() + no;
			}
			return maxcode;
		} catch (SQLException e) {

			throw e;
		} finally {
			DBUtil.close(rs, pstmt, conn);
		}
	}

	public Area(String areacode, String areaName, Integer grade) {
		super();
		this.areacode = areacode;
		this.areaName = areaName;
		this.grade = grade;
	}

	public int getGrade() {
		return grade;
	}

	public void setGrade(int grade) {
		this.grade = grade;
	}

	public String getAreacode() {
		return areacode;
	}

	public void setAreacode(String areacode) {
		this.areacode = areacode;
	}

	public String getAreaName() {
		return areaName;
	}

	public void setAreaName(String areaName) {
		this.areaName = areaName;
	}

	public List<Area> children() throws Exception {
		List<Area> areaList = new ArrayList<Area>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.getConn();
			pstmt = conn
					.prepareStatement("select * from area where areacode like'?%' and grade=?");
			int index = 1;
			pstmt.setString(index++, this.areacode);
			pstmt.setInt(index, this.grade + 1);
			rs = pstmt.executeQuery();

			while (rs.next()) {
				Area area = new Area();
				area.setAreacode(rs.getString("areaId"));
				area.setAreaName(rs.getString("areaPid"));
				area.setAreaName(rs.getString("areaName"));
				area.setGrade(rs.getInt("grade"));
				areaList.add(area);

			}

		} catch (SQLException e) {

			throw e;
		} finally {
			DBUtil.close(rs, pstmt, conn);
		}

		return areaList;
	}

	public static void main(String[] args) throws Exception {
		String number = "01";
		System.out.println(Integer.parseInt(number));

		System.out.println(String.format("%02d", Integer.parseInt(number)));
	}

}
